#include "videoplayer.h"
#include "QDebug"
#include <QMouseEvent>
#include <QApplication>
#include <QCoreApplication>

#ifdef Q_OS_WIN
#include <windows.h>
#endif

VideoPlayer::VideoPlayer(QString videoAddr, QWidget *parent) : QWidget(parent)
  , vlcInstance(nullptr)
  , mediaPlayer(nullptr)
{
    // 1. 初始化 libVLC
    const char* vlc_args[] = {
        "--no-xlib",
        "--plugin-path=C:/Users/Administrator/Desktop/vlc-3.0.12/plugins",
        "--novideo-title-show",
        "--no-audio",
        "--rtsp-tcp",
        "--network-caching=2000",
        "--sout-mux-caching=50",
        "--clock-jitter=0",
        "--clock-synchro=0",
    };
    vlcInstance = libvlc_new(sizeof(vlc_args) / sizeof(vlc_args[0]), vlc_args);

    addrHead = videoAddr;
}


void VideoPlayer::setVideo(QString streamerCode){

    if (!vlcInstance) {
        qDebug() << "Failed to create VLC instance!";
        return;
    }

    QString streamerAddr = addrHead + streamerCode;

    // 2. 创建媒体对象（RTMP 地址）
    libvlc_media_t *media = libvlc_media_new_location(vlcInstance,
        streamerAddr.toStdString().c_str());   // 服务器

    if (!media) {
        qDebug() << "Failed to create media!";
        return;
    }

    // 3. 创建播放器
    mediaPlayer = libvlc_media_player_new_from_media(media);

    // 释放 media 对象，mediaPlayer 内部已经保留引用
    libvlc_media_release(media);

    // 5. 绑定到 videoWidget
    libvlc_media_player_set_hwnd(mediaPlayer, (void*)this->winId());

    play();
}


void VideoPlayer::play(){

    // 开始播放
    libvlc_media_player_play(mediaPlayer);
}

void VideoPlayer::pause(){
    libvlc_media_player_pause(mediaPlayer);
}

void VideoPlayer::mousePressEvent(QMouseEvent *event){
    qDebug() << "mouse clicked";
    if(event->button() == Qt::LeftButton){
        if(libvlc_media_player_is_playing(mediaPlayer) == 1)
            pause();
        else
            play();
    }
}

VideoPlayer::~VideoPlayer(){
    if (mediaPlayer) {
        libvlc_media_player_stop(mediaPlayer);
        libvlc_media_player_release(mediaPlayer);
    }
    if (vlcInstance) {
        libvlc_release(vlcInstance);
    }
}
